package com.taxx.service.impl;

import com.alibaba.excel.EasyExcel;
import com.taxx.entity.DataUploadRecord;
import com.taxx.excel.IncomeExcelData;
import com.taxx.excel.IdentityExcelData;
import com.taxx.excel.PlatformExcelData;
import com.taxx.excel.listener.ExcelListenerFactory;
import com.taxx.excel.listener.IncomeExcelListener;
import com.taxx.excel.listener.IdentityExcelListener;
import com.taxx.excel.listener.PlatformExcelListener;
import com.taxx.service.DataUploadRecordService;
import com.taxx.service.ExcelImportService;
import com.taxx.util.ExcelTemplateValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Excel导入服务实现类
 *
 * @author taxx
 * @since 2024-01-01
 */
@Slf4j
@Service
public class ExcelImportServiceImpl implements ExcelImportService {

    @Autowired
    private DataUploadRecordService dataUploadRecordService;

    @Autowired
    private ExcelListenerFactory excelListenerFactory;

    /**
     * 文件上传目录
     */
    private static final String UPLOAD_DIR = "uploads";

    @Override
    public Map<String, Object> importIncomeExcel(MultipartFile file, Long userId, String startTime, String endTime) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先进行模板校验
            ExcelTemplateValidator.ValidationResult validationResult = ExcelTemplateValidator.validateIncomeTemplate(file);
            if (!validationResult.isValid()) {
                result.put("success", false);
                result.put("message", "模板校验失败：" + validationResult.getMessage());
                return result;
            }
            
            // 保存文件
            String fileName = saveFile(file);

            // 创建上传记录
            DataUploadRecord record = createUploadRecord(file, fileName, userId, "income");
            dataUploadRecordService.save(record);

            // 使用工厂创建新的监听器实例
            IncomeExcelListener listener = excelListenerFactory.createIncomeListenerWithService();

            // 设置时间参数
            listener.setTimeParams(startTime, endTime);

            // 使用EasyExcel读取文件
            EasyExcel.read(file.getInputStream(), IncomeExcelData.class, listener).sheet().doRead();

            // 获取导入结果
            IncomeExcelListener.ImportResult importResult = listener.getImportResult();

            // 更新上传记录
            record.setTotalCount(importResult.getTotalCount());
            record.setSuccessCount(importResult.getSuccessCount());
            record.setFailCount(importResult.getFailCount());
            record.setStatus(importResult.getFailCount() == 0 ? 1 : 2);
            if (importResult.getFailCount() > 0) {
                record.setErrorMessage(String.join("，", importResult.getErrorMessages()));
            }
            dataUploadRecordService.updateById(record);

            // 设置返回结果
            result.put("success", true);
            result.put("message", "收入信息导入完成");
            result.put("totalCount", importResult.getTotalCount());
            result.put("successCount", importResult.getSuccessCount());
            result.put("failCount", importResult.getFailCount());
            result.put("errorMessages", importResult.getErrorMessages());

            log.info("收入信息Excel导入完成，文件：{}，成功：{}，失败：{}", fileName, importResult.getSuccessCount(), importResult.getFailCount());

        } catch (Exception e) {
            log.error("收入信息Excel导入失败", e);
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> importIdentityExcel(MultipartFile file, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先进行模板校验
            ExcelTemplateValidator.ValidationResult validationResult = ExcelTemplateValidator.validateIdentityTemplate(file);
            if (!validationResult.isValid()) {
                result.put("success", false);
                result.put("message", "模板校验失败：" + validationResult.getMessage());
                return result;
            }
            
            // 保存文件
            String fileName = saveFile(file);

            // 创建上传记录
            DataUploadRecord record = createUploadRecord(file, fileName, userId, "identity");
            dataUploadRecordService.save(record);

            // 使用工厂创建新的监听器实例
            IdentityExcelListener listener = excelListenerFactory.createIdentityListenerWithService();

            // 使用EasyExcel读取文件
            EasyExcel.read(file.getInputStream(), IdentityExcelData.class, listener).sheet().doRead();

            // 获取导入结果
            IdentityExcelListener.ImportResult importResult = listener.getImportResult();

            // 更新上传记录
            record.setTotalCount(importResult.getTotalCount());
            record.setSuccessCount(importResult.getSuccessCount());
            record.setFailCount(importResult.getFailCount());
            record.setStatus(importResult.getFailCount() == 0 ? 1 : 2);
            if (importResult.getFailCount() > 0) {
                record.setErrorMessage(String.join("， ", importResult.getErrorMessages()));
            }
            dataUploadRecordService.updateById(record);

            // 设置返回结果
            result.put("success", true);
            result.put("message", "身份信息导入完成");
            result.put("totalCount", importResult.getTotalCount());
            result.put("successCount", importResult.getSuccessCount());
            result.put("failCount", importResult.getFailCount());
            result.put("errorMessages", importResult.getErrorMessages());

            log.info("身份信息Excel导入完成，文件：{}，成功：{}，失败：{}", fileName, importResult.getSuccessCount(), importResult.getFailCount());

        } catch (Exception e) {
            log.error("身份信息Excel导入失败", e);
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> importPlatformExcel(MultipartFile file, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先进行模板校验
            ExcelTemplateValidator.ValidationResult validationResult = ExcelTemplateValidator.validatePlatformTemplate(file);
            if (!validationResult.isValid()) {
                result.put("success", false);
                result.put("message", "模板校验失败：" + validationResult.getMessage());
                return result;
            }
            
            // 保存文件
            String fileName = saveFile(file);

            // 创建上传记录
            DataUploadRecord record = createUploadRecord(file, fileName, userId, "platform");
            dataUploadRecordService.save(record);

            // 使用工厂创建新的监听器实例
            PlatformExcelListener listener = excelListenerFactory.createPlatformListenerWithService();

            // 使用EasyExcel读取文件
            EasyExcel.read(file.getInputStream(), PlatformExcelData.class, listener).sheet().doRead();

            // 获取导入结果
            PlatformExcelListener.ImportResult importResult = listener.getImportResult();

            // 更新上传记录
            record.setTotalCount(importResult.getTotalCount());
            record.setSuccessCount(importResult.getSuccessCount());
            record.setFailCount(importResult.getFailCount());
            record.setStatus(importResult.getFailCount() == 0 ? 1 : 2);
            if (importResult.getFailCount() > 0) {
                record.setErrorMessage(String.join("，", importResult.getErrorMessages()));
            }
            dataUploadRecordService.updateById(record);

            // 设置返回结果
            result.put("success", true);
            result.put("message", "平台信息导入完成");
            result.put("totalCount", importResult.getTotalCount());
            result.put("successCount", importResult.getSuccessCount());
            result.put("failCount", importResult.getFailCount());
            result.put("errorMessages", importResult.getErrorMessages());

            log.info("平台信息Excel导入完成，文件：{}，成功：{}，失败：{}", fileName, importResult.getSuccessCount(), importResult.getFailCount());

        } catch (Exception e) {
            log.error("平台信息Excel导入失败", e);
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 保存文件
     */
    private String saveFile(MultipartFile file) throws IOException {
        // 创建上传目录
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        // 保存文件
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);

        return fileName;
    }

    /**
     * 创建上传记录
     */
    private DataUploadRecord createUploadRecord(MultipartFile file, String fileName, Long userId, String dataType) {
        DataUploadRecord record = new DataUploadRecord();
        record.setFileName(file.getOriginalFilename());
        record.setFilePath(UPLOAD_DIR + File.separator + fileName);
        record.setFileSize(file.getSize());
        record.setUploadUserId(userId);
        record.setUploadTime(LocalDateTime.now());
        record.setDataType(dataType);
        record.setStatus(0); // 处理中
        return record;
    }
}
